<?php

namespace App\Http\Controllers\Admin;
use App\Model\Area;
use App\Model\Checkcategory;
use App\Model\Checkentry;
use App\Model\Checknegative;
use App\Model\Comcheck;
use App\Model\Comcheckagain;
use App\Model\Comcheckagaindetail;
use App\Model\Comcheckdetail;
use App\Model\Company;
use App\Model\Xtprovince;
use App\Model\Xtcity;
use App\Model\Xttown;
use App\Model\Xtstreet;
use App\Model\MessageText;
use App\Model\Message;
use App\Model\MessageLogging;
use App\Model\CheckListLog;
use App\Model\CheckListMsg;
use App\Model\Job;
use App\Model\Department;
use App\Model\Users as User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Admin\UploadClass;
class MessageController extends Controller
{

    // 应急管理局
    // 公安局
    // 城市管理和综合行政执法局
    // 市场监管局
    // 消防救援大队
    // 教育和体育局
    // 工业和信息化局
    // 商务局
    // 文化和旅游局
    // 卫生健康局
    // 旧版
    // protected $role_type = ['emergency','policea','policeb','enforcement','supervise','rescue'];
    // protected $role_type_name = ['emergency'=>'石臼街道应急管理事务服务中心','policea'=>'黄海路派出所','policeb'=>'石臼派出所','enforcement'=>'综合行政执法石臼中队','supervise'=>'石臼市场监管所','rescue'=>'东港消防救援大队'];
    // protected $role_type_name1 = ['石臼街道应急管理事务服务中心'=>'emergency','黄海路派出所'=>'policea','石臼派出所'=>'policeb','综合行政执法石臼中队'=>'enforcement','石臼市场监管所'=>'supervise','东港消防救援大队'=>'rescue'];
    // // 消息列表页
    // 新版
    protected $role_type = ['emergency','policea','enforcement','supervise','rescue','sports','miit','business','travel','hygiene'];
    protected $role_type_name = [
        'emergency'=>'应急管理局',
        'policea'=>'公安局',
        'enforcement'=>'城市管理和综合行政执法局',
        'supervise'=>'市场监管局',
        'rescue'=>'消防救援大队',
        'sports'=>'教育和体育局',
        'miit'=>'工业和信息化局',
        'business'=>'商务局',
        'travel'=>'文化和旅游局',
        'hygiene'=>'卫生健康局',
    ];
    protected $role_type_name1 = [
        '应急管理局'=>'emergency',
        '公安局'=>'policea',
        '城市管理和综合行政执法局'=>'enforcement',
        '市场监管局'=>'supervise',
        '消防救援大队'=>'rescue',
        '教育和体育局'=>'sports',
        '工业和信息化局'=>'miit',
        '商务局'=>'business',
        '文化和旅游局'=>'travel',
        '卫生健康局'=>'hygiene',
    ];
   

    public function list(){
        return view('admin/message/list');
    }
   
    // 角色 应急:emergency  派出所:policea  policeb  综合行政执法石臼中队:emergency 石臼市场监管所:supervise 消防:rescue
    public function listdata(Request $request){
        $status = $request->input('status');
        $is_handle = $request->input('is_handle');
        $type = $request->input('type');
        $data = [];
        $role = Auth::guard('admin')->user()->role;
        // dump($role);exit;
        $query=MessageLogging::orderBy('id','desc')->orderBy('status','asc');
        
        if($status && $status >0){
            $query->where('status',$status-1);
        }
        if($is_handle && $is_handle >0){
            $query->where('is_handle',$is_handle-1);
        }
        if($type >0){
            $query->where('type',$type);
        }
        if(in_array($role ,$this->role_type)){
            // $query->where('from_role',$role)->orWhere('to_role',$role);
            $query->where(function($query) use ($role){
                $query->where('from_role','=',$role)->orWhere('to_role','=',$role);
            });
        }
        // 查询当前登录用户的街道  暂时不查询社区
        $street = Auth::guard('admin')->user()->street;
        if($street){
            // 如果街道信息存在，则查询所有这个街道的消息
            $query->where('street',$street);
        }
        
    	$data = $query->paginate($request->get('limit',15))->toArray();
        foreach ($data['data'] as &$v){
            // 查询企业信息
            $comdata = Company::where('id',$v['company_id'])->first();
            if(empty($comdata)){
                // 无营业执照的没有公司ID 公司名称暂时使用content存储
                $v['comName'] = $v['content'];
                $v['leader'] = '无营业执照暂不可显示';
                $v['address'] = '无营业执照暂不可显示';

            }else{
                $v['comName'] = !empty($comdata['comName'])?$comdata['comName']:'';
                $v['leader'] = !empty($comdata['leader'])?$comdata['leader']:'';
                $v['address'] = !empty($comdata['address'])?$comdata['address']:'';
            }
            $area = Area::where('id',$comdata['district'])->pluck('name')->first();

           
            $v['areaname'] = $area;
            $from = User::where('id',$v['from_user_id'])->pluck('name')->first();
            $v['from_name'] = $from;
            $v['status_name'] = $v['status']==1?'已确认':'未确认';
            if(empty($v['relation_message_id'])){
                $v['handle_name'] = $this->getHandelStatus($v['id']);
            }else{
                $v['handle_name'] = $v['is_handle']==1?'已处理':'未处理';
            }
            // 查询发送人角色信息
            // $v['from_role_name'] = $this->role_type_name($v['from_role']);//发送人角色


            // 查询接收人信息
            $to = User::where('id',$v['to_user_id'])->pluck('name')->first();
            $v['to_name'] = !empty($to)?$to:$this->role_type_name[$v['to_role']];
            $v['relation_message_id'] = !empty($v['relation_message_id'])?$v['relation_message_id']:0;
            //判断消息是否是无营业执照类别
            $v['handle'] = ($v['type']==1)?1:($v['relation_message_id']?$v['relation_message_id']:0);
            // 是否可转发
            $v['f_status'] = $this->getForward($v['id']);

            // 按照当前登录人，当前登录人转发的消息，不显示操作按钮（原来的逻辑暂时不做处理）

            $v['choose_status'] = $this->getchoose_status($role,$v['id'],$v['relation_message_id']);
            // 当前登录人是发送人或者接收人且是派出所+应急中心的的时候显示处理按钮
            $v['choose_status1'] = in_array($v['from_role'],['policea','policeb','emergency']) ?1:0;
            if($v['choose_status1'] ==1){
                if($v['is_handle'] == 1){
                    $v['choose_status1'] = 0;
                }
            }
            if($v['type'] ==1){
                // $v['choose_status1'] =1;//无营业执照的，需要市场监管直接处理，需要显示处理按钮则将该行的屏蔽打开
            }
            if($v['grid_id']){
                // 查询网格员信息

                $v['grid'] = User::where('id',$v['grid_id'])->pluck('name')->first().'-'.User::where('id',$v['grid_id'])->pluck('phone')->first();//网格员信息
            }else{
                $v['grid'] = '';//网格员信息
            }
            
        }
        $data = [
            'code' => 0,
            'msg'   => '请求成功',
            'count' => $data['total'],
            'data'  => $data['data']
        ];
        // dump($data);exit;
        return response()->json($data);
        
    }

    public function getchoose_status($role,$id,$relation_message_id){
        // relation_message_id原消息ID，role 当前登录角色，id 需要判断的消息ID
        // c查询原消息的接收人是否是当前登录人
        $to_role = MessageLogging::where('id',$relation_message_id)->pluck('to_role')->first();
        if($role == $to_role){
            return 1;//1为不显示其他4个操作按钮
        }
        return 0;

    }

    // 查询转发的消息是否全部处理完成
    public function getHandelStatus($id){

        $message = MessageLogging::where('id',$id)->first();
        if($message['type'] ==1){
            if($message['is_handle']==1){
                return '已处理';
            }else{
                return '未处理';
            }
        }
        $data = MessageLogging::where('relation_message_id',$id)->get()->toArray();

        $a = 0;
        $b = 0;
        $title = '未全部处理';
        
        foreach ($data as $key=>$val){
            if($val['is_handle'] == 1){
                $a++;//已处理
            }else{
                $b++;//未处理
            }
        }

        if($b>0){
            if($b == count($data)){
                $title = '未处理';
            }else{
                $title = '未全部处理';
            }
        }
        if($a>0){
            if($a==count($data)){
                $title = '已处理';
                // 将原来的消息状态直接更改为已处理
                $message1=MessageLogging::find($id);
                $message1->is_handle=1;
                $res = $message1->save();
            }else{
                $title = '未全部处理';  
            }
        }
        return $title;
    }

    // 查询是否可以转发
    public function getForward($id){
        $a = MessageLogging::where('id',$id)->first()->toArray();
        if($a['type'] ==1){
            // 1是无营业执照类别的消息，不可以转发
            return 1;
        }
        
        if($a['relation_message_id']){
                $res = MessageLogging::where('relation_message_id',$a['relation_message_id'])->where('to_role','rescue')->first();
                if($res){
                    return 1;
                }
            }
        // $b = MessageLogging::where('relation_message_id',$id)->first()->toArray();
        // if($b){
        //     // 该消息已经转发过 ，更改为不可转发
        //     return 1;
        // }
        return 0;
    }

    // 确认接受消息

    public function msgyes(Request $request){
        $id = $request->input('id');
        $message=MessageLogging::find($id);
        $message->status=1;
        $res = $message->save();
        if($res){
            $data=[
                'code'=>1,
                'msg'=>'消息确认成功'
            ];
            return response()->json($data);
        }else{
            $data=[
                'code'=>1,
                'msg'=>'消息确认失败'
            ];
            return response()->json($data);
        }

    }

    /**
     * @param Request $quest
     * @return mixed
     */
    public function reportones(Request $quest){
        $cityname = '日照市';
        $area_first = array();
        $area_first = Area::where('name','日照市')->first()->toArray();
        $parent_path = $area_first['node'].','.$area_first['id'];
        $where = array();
        $where[] = array('node', 'like', $parent_path.'%');
        $area = Area::where($where)->select(array('id','pid','node','name','level'))->get()->toArray();
        $tree = $this->getProvinceTree($area_first, $area);
        $companyId = $quest->input('id');
        $company =  Company::find($companyId);
        $comcheck = Comcheck::leftJoin('users','comcheck.userId','users.id')->select('comcheck.*','users.name')->where(['comcheck.companyId' => $companyId])->get();
        if (empty(json_decode(json_encode($comcheck), true))) {
            echo "<script>alert('该公司还未检查');history.go(-1);</script>";
            exit();
        }
		
        $comcheckdetail = CheckListLog::where(['comcheck_id'=>$comcheck[0]->id])->where(['is_danger'=>1])->get()->toarray();
        $is = !empty($comcheckdetail)?1:0;
        if (!empty($comcheckdetail)) {        //有异常需要整改
            //获取异常点
            $negatives = [];
            foreach ($comcheckdetail as $k=>$v){
                if (!empty($v['negatives'])){
                    $arr = explode(',',$v['negatives']);
                    foreach ($arr as $ar){
                        if (!empty($ar)){
                            array_push($negatives,$ar);
                        }
                    }
                }
            }
            $negatives = Checknegative::whereIn('id',$negatives)->get();
            $comcheckagain = Comcheckagain::where(['checkId'=>$comcheck[0]->id])->get();
            if (!empty(json_decode(json_encode($comcheckagain), true))){
                $comcheckagainId = $comcheckagain[0]->id;
                $comcheckagaindetail = Comcheckagaindetail::where(['checkId'=>$comcheckagainId])->where(['status'=>1])->get();
                $comcheckagaindetail = json_decode(json_encode($comcheckagaindetail), true);
                $again = empty($comcheckagaindetail)?1:0;
            }else{
                $again = 1;
            }
        }else{
            $again = 1;         //不存在隐患不需要整改整改状态正常
            $negatives = '';
        }
        $negatives = json_decode(json_encode($negatives), true);
        $categoryname = empty($company->categoryId)?'':Checkcategory::find($company->categoryId)->name;
        $address = (empty($company->province)?'':(Area::find($company->province)->name)).(empty($company->city)?'':(Area::find($company->city)->name)).(empty($company->district)?'':(Area::find($company->district)->name)).(empty($company->street)?'':(Area::find($company->street)->name)).(empty($company->community)?'':(Area::find($company->community)->name)).$company->address;
        $shequ = empty($company->community)?'':Area::find($company->community)->name;

        return view('admin/message/reportones')
            ->with('comcheck',$comcheck)
            ->with('tree',$tree)
            ->with('address',$address)
            ->with('categoryname',$categoryname)
            ->with('shequ',$shequ)
            ->with('companyId',$companyId)
            ->with('negatives',$negatives)
            ->with('again',$again)
            ->with('is',$is)
            ->with('company',$company);
    }

    /**
     * @param $area_first
     * @param $area
     * @return mixed
     */
    protected function getProvinceTree($area_first,$area)
    {
        $area_tree = $area_first;
        $district_street = array();
        $community = array();
        foreach($area as $k=>$v) {
            if($v['level']!=5) {
                $district_street[] = $v;
            } else {
                $community[] = $v;
            }
        }
        $district_street = array_column($district_street, null, 'id');
        $community_arr = array();
        foreach ($community as $key => $value) {
            $community_arr[$value['pid']][] = $value;
        }
        /*获取市的各区*/
        foreach($district_street as $k=>$v) {
            if($v['level']==3 && $v['name'] == '东港区') {
                $area_tree['district'][] = $v;
            }
        }
        /*获取街道*/
        foreach ($area_tree['district'] as $key => $value) {
            foreach($district_street as $k=>$v) {
                if($value['id']==$v['pid']) {
                    $area_tree['district'][$key]['street'][] = $v;
                }
            }
        }
        /*获取社区*/
        foreach($area_tree['district'] as $k=>$v) {
            foreach($v['street'] as $key=>$value) {
                if(isset($community_arr[$value['id']])) {
                    $area_tree['district'][$k]['street'][$key]['community'] = $community_arr[$value['id']];
                } else {
                    $area_tree['district'][$k]['street'][$key]['community'] = array();
                }
            }
        }
        return $area_tree;
    }

    // 转发
    // 角色 应急:emergency  派出所:policea  policeb  综合行政执法石臼中队:emergency 石臼市场监管所:supervise 消防:rescue
    // 石臼街道应急管理事务服务中心消息下发到派出所a、派出所b、综合行政执法石臼中队、石臼市场监管所
    // 派出所消息发送给东港消防救援大队
    public function forward(Request $request){
        $id = $request->input('id');
        
        // 根据消息id的复查id及企业ID查询隐患信息
        $danger_data = $this->getDangerData($id);
        // dump($danger_data);exit;
        // 查询当前登录人角色，根据角色判断可转发的角色组信息
        $role = Auth::guard('admin')->user()->role;
        if($role == 'emergency'){
            // $roles =['黄海路派出所','石臼派出所','综合行政执法石臼中队','石臼市场监管所','东港消防救援大队'];
            // $roles = [['id'=>1,'name'=>'黄海路派出所'],['id'=>1,'name'=>'石臼派出所'],['id'=>3,'name'=>'综合行政执法石臼中队'],['id'=>4,'name'=>'石臼市场监管所'],['id'=>5,'name'=>'东港消防救援大队']];

            $roles = [
                ['id'=>1,'name'=>'公安局'],
                ['id'=>2,'name'=>'城市管理和综合行政执法局'],
                ['id'=>3,'name'=>'市场监管局'],
                ['id'=>4,'name'=>'消防救援大队'],
                ['id'=>5,'name'=>'教育和体育局'],
                ['id'=>6,'name'=>'工业和信息化局'],
                ['id'=>7,'name'=>'商务局'],
                ['id'=>8,'name'=>'文化和旅游局'],
                ['id'=>9,'name'=>'卫生健康局'],
            ];
        }else if(($role == 'policea') || ($role == 'policeb')){
            // 查询该消息是否已直接转发东港消防救援大队
            $a = MessageLogging::where('id',$id)->first()->toArray();
            if($a['relation_message_id']){
                $res = MessageLogging::where('relation_message_id',$a['relation_message_id'])->where('to_role','rescue')->first();
                if($res){
                    return redirect()->to(route('admin.message.list'))->with(['status'=>'该消息已转发东港消防救援大队，不可再次操作']);
                }
            }
            
            $roles = [['id'=>1,'name'=>'消防救援大队']];
        }else{
            // $roles = [
            //     // ['id'=>1,'name'=>'policea'],['id'=>2,'name'=>'policeb'],['id'=>3,'name'=>'emergency'],['id'=>4,'name'=>'supervise'],['id'=>5,'name'=>'rescue']
                
            // ];
            // $roles = [['id'=>1,'name'=>'黄海路派出所'],['id'=>1,'name'=>'石臼派出所'],['id'=>3,'name'=>'综合行政执法石臼中队'],['id'=>4,'name'=>'石臼市场监管所'],['id'=>5,'name'=>'东港消防救援大队']];
            $roles = [
                ['id'=>1,'name'=>'公安局'],
                ['id'=>2,'name'=>'城市管理和综合行政执法局'],
                ['id'=>3,'name'=>'市场监管局'],
                ['id'=>4,'name'=>'消防救援大队'],
                ['id'=>5,'name'=>'教育和体育局'],
                ['id'=>6,'name'=>'工业和信息化局'],
                ['id'=>7,'name'=>'商务局'],
                ['id'=>8,'name'=>'文化和旅游局'],
                ['id'=>9,'name'=>'卫生健康局'],
            ];
        }
        $path = base_path().'/public/xmSelect.js';
        
        // dump($path);exit;
        return view('admin/message/forward')
        ->with('roles',$roles)
        ->with('danger_data',$danger_data)
        ->with('message_id',$id)
        ->with('path',$path);
    }


    // 获取隐患信息
    public function getDangerData($id){
        // 顺带生成消息ID与隐患信息的关联关系

        $message=MessageLogging::find($id);
        if($message['danger_ids']){
            $ids = explode(',',$message['danger_ids']);
            $dangers = CheckListLog::whereIn('id',$ids)->get();
        }else{
            // $dangers = CheckListLog::where(['company_id'=>$message->company_id,'check_type'=>2,'comcheck_id'=>$message->comcheck_again_id])->orderBy('id','desc')->limit(27)->get();
            $dangers = CheckListLog::where(['company_id'=>$message->company_id,'comcheck_id'=>$message->comcheck_again_id,'check_type'=>2])->orderBy('id','desc')->limit(34)->get();
            
        }
            $dangers_data = [];
            // dump($dangers);exit;
            foreach ($dangers as $key=>$val){
                if(!empty($val['title'])){
                    
                    // dump($val['option']);exit;
                    if($val['is_danger']==1){
                        $val['problem'] = !empty($val['problem'])?$val['problem']:'';
                        $val['option'] = $val['option'] == 0 ?'是':'否';
                        // 是隐患需要转发
                        
                        // 查询是否已经存在不存在则添加存在则不处理
                        $a = CheckListMsg::where(['message_id'=>$id,'list_id'=>$val['id']])->first();
                        if(empty($a)){
                            CheckListMsg::insertGetId(['message_id'=>$id,'list_id'=>$val['id']]);
                        }
                        $dangers_data[] = $val;
                    }
                    
                }
                
            }
        // dump($dangers_data);exit;
        return $dangers_data;
    }


    // 处理权限相关的对应关系的
    public function getRoles($roles,$danger_id){
        $data = [];
        foreach($roles as $k=>$v){
            $name = $this->role_type_name1[$v];
            $a['name'] = $name;
            $a['id'] = $danger_id;
            $data[] = $a;

        }
        return $data;
    }

    public function forwardaction(Request $request){
        $data = $request->input();
        

        // 遍历处理数组

        // dangers隐患
        $dangers = $data['dangers'];
        
        foreach($dangers as $k=>$v){
            // dump(isset($data['roles'.$v]));
            if( isset($data['roles'.$v])){
                $a = $this->getRoles($data['roles'.$v],$v);
                $roles[] = $a;
            }else{
                $roles[] = [];
            }
            
        }
        // exit;
        $role_data = ['emergency'=>'','policea'=>'','policeb'=>'','enforcement'=>'','supervise'=>'','rescue'=>'','sports'=>'','miit'=>'','business'=>'','travel'=>'','hygiene'=>''];
        // 循环数据.
        // 应急:emergency  派出所:policea  policeb  综合行政执法石臼中队:emergency 石臼市场监管所:supervise 消防:rescue
        foreach($roles as $kk=>$vv){
            // 二次处理
            foreach ($vv as $k=>$v){
                if($v['name'] == 'emergency'){
                    $role_data['emergency'] = empty($role_data['emergency'])? $role_data['emergency'].$v['id'] : $role_data['emergency'].','.$v['id'];
                }
                if($v['name'] == 'policea'){
                    $role_data['policea'] = $role_data['policea'].','.$v['id'];
                }
                if($v['name'] == 'policeb'){
                    $role_data['policeb'] = $role_data['policeb'].','.$v['id'];
                }
                if($v['name'] == 'enforcement'){
                    $role_data['enforcement'] = $role_data['enforcement'].','.$v['id'];
                }
                if($v['name'] == 'supervise'){
                    $role_data['supervise'] = $role_data['supervise'].','.$v['id'];
                }
                if($v['name'] == 'rescue'){
                    $role_data['rescue'] = $role_data['rescue'].','.$v['id'];
                }
                if($v['name'] == 'sports'){
                    $role_data['sports'] = $role_data['sports'].','.$v['id'];
                }
                if($v['name'] == 'miit'){
                    $role_data['miit'] = $role_data['miit'].','.$v['id'];
                }
                if($v['name'] == 'business'){
                    $role_data['business'] = $role_data['business'].','.$v['id'];
                }
                if($v['name'] == 'travel'){
                    $role_data['travel'] = $role_data['travel'].','.$v['id'];
                }
                if($v['name'] == 'hygiene'){
                    $role_data['hygiene'] = $role_data['hygiene'].','.$v['id'];
                }
            }
        }

        // dump($role);exit;
        $message_id = $data['message_id'];
        if(empty($data)){
            return redirect()->to(route('admin.message.list'));
        }
        // 判断作废
        if(!empty($data['message_id']) && empty($data['roles'])){
            // return redirect()->to(route('admin.message.list'))->with(['status'=>'未选择任何接收人，无法转发']);
        }
        // 之前的接收数据，逻辑改了用不到了
        // $roles = $data['roles'];
        
        $role = Auth::guard('admin')->user()->role;//当前角色
        $user_id = Auth::guard('admin')->user()->id;//当前用户ID
        $message = MessageLogging::where('id',$message_id)->first()->toArray();
        // dump((in_array($this->role_type_name1['黄海路派出所'],$roles) && in_array('rescue',$roles)));exit;
        // if((in_array($this->role_type_name['policea'],$roles) && in_array($this->role_type_name['rescue'],$roles)) || (in_array($this->role_type_name['policeb'],$roles) && in_array($this->role_type_name['rescue'],$roles)) ){
        //     return redirect()->to(route('admin.message.list'))->with(['status'=>'公安局与东港消防救援大队不可以同时选择']);
        // }
        if((in_array($this->role_type_name['policea'],$roles) && in_array($this->role_type_name['rescue'],$roles)) ){
            return redirect()->to(route('admin.message.list'))->with(['status'=>'公安局与东港消防救援大队不可以同时选择']);
        }
        // 遍历转发相关信息
        foreach ($role_data as $key => $value){
            if(!empty($value)){
                // 相关值不为空时才转发插入消息
                $res = MessageLogging::where('relation_message_id',$message_id)->where('to_role',$key)->first();
                if(!$res){
                    $msg_data = [
                        'title'=>$message['title'],
                        'content'=>$message['content'],
                        'from_user_id'=>$user_id,
                        'from_role'=>$role,
                        'to_role'=>$key,
                        'company_id'=>$message['company_id'],
                        'created'=>time(), 
                        'comcheck_id'=>$message['comcheck_id'],
                        'comcheck_again_id'=>$message['comcheck_again_id'],
                        'relation_message_id'=>$message_id,
                        'danger_ids'=>$value,
                        'grid_id'=>$message['from_user_id'],
                        'street'=>$message['street'],//街道
                        'community'=>$message['community'],//社区
        
                    ];
                    MessageLogging::insertGetId($msg_data);
                }
            }
            
            
        }
        return redirect()->to(route('admin.message.list'))->with(['status'=>'转发成功']);

    }
    // 处理  废弃
    public function handle_old(Request $request){
        $id = $request->input('id');
        $message=MessageLogging::find($id);
        $message->is_handle=1;
        $res = $message->save();
        if($res){
            // 处理关联消息的状态
            $a = $this->getHandelNums($message['relation_message_id']);
            if($a ==1){
                // 消息全部处理完成时，原消息状态更改为已处理
                $m = MessageLogging::find($message['relation_message_id']);

                $m->is_handle=1;
                $m->save();
            }
            
            $data=[
                'code'=>1,
                'msg'=>'处理成功'
            ];
            return response()->json($data);
        }else{
            $data=[
                'code'=>1,
                'msg'=>'处理失败'
            ];
            return response()->json($data);
        }
    }

    public function getHandelNums($id){

        $data = MessageLogging::where('relation_message_id',$id)->select();

        $a = 0;
        $b = 0;
        foreach ($data as $key=>$val){
            if($val['is_handle'] == 1){
                $a++;//已处理
            }else{
                $b++;//未处理
            }
        }
        if($b>0){
            if($b == count($data)){
                return 0;
            }else{
                return 0;
            }
        }
        if($a>0){
            if($a==count($data)){
                return 1;
            }else{
                return 0;
            }
        }
        
    }

    // 隐患信息查询  如果是消息接收人是派出所，那么隐患按钮里面的文书内容需要往下再查询一级
    public function handle(Request $request){
        $id = $request->input('id');
        $message = MessageLogging::find($id);
        // 根据消息id的复查id及企业ID查询隐患信息
        $danger_data = $this->getDangerData($id);
        // dump($danger_data);exit;
        $role = Auth::guard('admin')->user()->role;
        $resource_url = !empty($message['resource_url'])?$message['resource_url']:'http://'.$_SERVER['HTTP_HOST'].'/11.png';
        $remarks = !empty($message['remarks'])?$message['remarks']:'';
        // dump($message['from_role']);exit;
        // 当前登录人是消息的发送人的时候，隐患页面根据此状态隐藏确定按钮
        $choose_status = ($message['from_role']==$role)?0:1;
        $resource_data = [];
        if(in_array($message['from_role'],['policea','policeb'])){
            $resource_data = MessageLogging::where('relation_message_id',$id)->get();

        }
        // 再往下查询1级，文书及备注信息

        // dump($choose_status ==1);exit;
        // $id为消息的id
        return view('admin/message/handle')
        ->with('danger_data',$danger_data)
        ->with('resource_url',$resource_url)
        ->with('resource_data',$resource_data)
        ->with('remarks',$remarks)
        ->with('choose_status',$choose_status)
        ->with('message_id',$id);
    }
// 新版隐患 上传文书内容及备注
    public function handleaction(Request $request){
        $id = $request->input('message_id');//消息ID
        $resource_url = $request->input('thumb');
        $remarks = $request->input('remarks');
        $message=MessageLogging::find($id);
        $message->resource_url=$resource_url;
        $message->remarks=$remarks;
        $message->is_handle=1;
        $res = $message->save();
        if($res){    
            // 处理关联消息的状态 仅限派出所及应急中心为发送人角色之外的消息这样处理
            if(!in_array($message['from_role'],['policea','policeb','emergency'])){
                $a = $this->getHandelNums($message['relation_message_id']);
                if($a ==1){
                    // 消息全部处理完成时，原消息状态更改为已处理
                    $m = MessageLogging::find($message['relation_message_id']);
    
                    $m->is_handle=1;
                    $m->save();
                } 
            }
            
            return redirect()->to(route('admin.message.list'))->with(['status'=>'处理成功']);
        }else{
            return redirect()->to(route('admin.message.list'))->with(['status'=>'处理失败']);
        }


    }

    // 文书图片上传
    public function upload(Request $request){
        $upload = new UploadClass(); 
        $upload->savePath='storage/images'; 
        $file = $request->file('file'); 
        $url = $upload->upload($file); 
        
        if(!$url){
                $data['info'] = $upload->getError();
                $data['filepath'] = '';
        }
        $data['filepath'] = $url;
        
        return response()->json($data);
        
    }
    // 消息附件上传
    public function uploadfile(Request $request){
        $upload = new UploadClass(); 
        $upload->maxSize=5*1024*1024;
        $upload->savePath='storage/images'; 
        $file = $request->file('file'); 
        $url = $upload->upload($file); 
        
        if(!$url){
                $data['info'] = $upload->getError();
                $data['filepath'] = '';
        }
        $data['filepath'] = $url;
        
        return response()->json($data);
        
    }
}
